/*
 * Copyrignt (c) xuzeshui.com. All Rights Reserved.
 * Author: Xiaobao Zeng<zengxiaobao@skyworth.com>
 * Created Time: 2017-03-30 15:38:57
 * Last Modified: 2017-07-24 09:04:09
 * File Name: league.go
 * Description:
 */

package admin

import (
	"errors"
	"fmt"
	"strconv"
	"strings"

	"qkleague/db"
	"qkleague/errorcode"

	"doubimeizhi.com/datatable"
	"doubimeizhi.com/utility"
	log "github.com/cihub/seelog"
)

var adminServiceInstance *adminService

type adminService struct{}

func GetAdminService() *adminService {
	if adminServiceInstance == nil {
		adminServiceInstance = &adminService{}
	}
	return adminServiceInstance
}

func (p *adminService) ListLeague(req *ShowItemReq, resp *ShowItemResp, ltype int, key string) error {
	dtq := p.leagueDtq(ltype, key)
	sql, val := dtq.GenerateSQL()
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, val...)
	if err == nil {
		if len(results) == 0 {
			log.Warnf("查询没有此信息的加盟商，datafilter by %d, %s is empty", ltype, key)
		}
		for _, dt := range results {
			li := p.leagueParseRecords(mysqlHelper, dt)
			resp.Data = append(resp.Data, li)
		}
	} else {
		log.Errorf("mysql err sql:%s, err:%s", sql, err.Error())
	}

	if !req.Role {
		s, v := dtq.GenerateTotalRecordSQL("total_records")
		if results, err := mysqlHelper.Query(s, v...); err == nil {
			if len(results) > 0 {
				resp.Total = mysqlHelper.GetColInt(results[0], "total_records")
			}
		} else {
			log.Errorf("mysql err sql:%s, values:%v", err.Error(), v)
		}
	}
	if resp.Total > resp.PageSize {
		resp.HasMore = true
	}
	resp.Code = errorcode.EC_GL_SUCCESS
	resp.Msg = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	resp.PageIndex = req.PageIndex
	return nil
}

func (p *adminService) GetSomeLeague(ltype int, key string) (error, []*QKLeague) {
	resp := make([]*QKLeague, 0)
	dtq := p.leagueDtq(ltype, key)
	sql, val := dtq.GenerateSQL()
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, val...)
	if err == nil {
		if len(results) == 0 {
			log.Warnf("查询没有此信息的加盟商， QKLeague empty!! ltype:%d, key:%s", ltype, key)
			return errors.New("查询没有此信息的加盟商"), nil
		}
		for _, dt := range results {
			resp = append(resp, p.leagueParseRecords(mysqlHelper, dt))
		}
		return nil, resp
	} else {
		log.Errorf("mysql err sql:%s, err:%s", sql, err.Error())
	}
	return errors.New("数据库查询失败"), nil
}

func getWashRoomNumByLeagueId(leagueId string) (int, []string) {
	sql := "select room_id from wash_room"
	if leagueId != "" {
		sql = fmt.Sprintf("%s where userid = '%s'", sql, leagueId)
	}
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	if results, err := mysqlHelper.Query(sql); err == nil {
		cnt := 0
		rooms := make([]string, 0, len(results))
		for _, dt := range results {
			cnt++
			rooms = append(rooms, mysqlHelper.GetColString(dt, "room_id"))
		}
		return cnt, rooms
	} else {
		log.Errorf("getWashRoomNumByLeagueId err, err:%s, league_id:%s", err.Error(), leagueId)
	}
	return 0, nil
}

func getWasherNumByLeagueId(rooms []string) int {
	sql := "select count(0) as nums from washer_info"
	sql = fmt.Sprintf("%s where room_id in (\"%s\")", sql, strings.Join(rooms, "\",\""))
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	if results, err := mysqlHelper.Query(sql); err == nil {
		return mysqlHelper.GetColInt(results[0], "nums")
	} else {
		log.Errorf("getWasherNumByLeagueId err, err:%s, washroom_ids:%v", err.Error(), rooms)
	}
	return 0
}

func (p *adminService) leagueDtq(ltype int, key string) *datatable.DataTableQuery {
	dtq := datatable.NewDataTableQuery()
	dtq.SetTableName("league_user")
	dtq.PushField(&datatable.FiledItem{Alias: "id", Field: "id"})
	dtq.PushField(&datatable.FiledItem{Alias: "userid", Field: "userid"})
	dtq.PushField(&datatable.FiledItem{Alias: "account_id", Field: "account_id"})
	dtq.PushField(&datatable.FiledItem{Alias: "nick_name", Field: "nick_name"})
	dtq.PushField(&datatable.FiledItem{Alias: "main_name", Field: "main_name"})
	dtq.PushField(&datatable.FiledItem{Alias: "region_addr", Field: "region_addr"})
	dtq.PushField(&datatable.FiledItem{Alias: "contact_peer", Field: "contact_peer"})
	dtq.PushField(&datatable.FiledItem{Alias: "mobile", Field: "mobile"})
	dtq.PushField(&datatable.FiledItem{Alias: "bank_account_name", Field: "bank_account_name"})
	dtq.PushField(&datatable.FiledItem{Alias: "bank_account", Field: "bank_account"})
	dtq.PushField(&datatable.FiledItem{Alias: "bank", Field: "bank"})
	key = strings.TrimSuffix(key, "")
	switch ltype {
	case 1:
		dtq.PushCondition("account_id=?", key)
	case 2:
		dtq.PushCondition("nick_name=?", key)

	case 3:
		dtq.PushCondition("main_name=?", key)

	case 4:
		id, _ := strconv.Atoi(key)
		dtq.PushCondition("id=?", id)
	case 5:
		dtq.PushCondition("userid=?", key)
	default:
	}
	return dtq
}

func (p *adminService) leagueParseRecords(mysqlHelper *utility.MySQLHelper, dt map[string]interface{}) *QKLeague {
	li := &QKLeague{}
	li.Id = mysqlHelper.GetColInt64(dt, "id")
	li.LeagueId = mysqlHelper.GetColString(dt, "userid")
	li.AccountId = mysqlHelper.GetColString(dt, "account_id")
	li.NickName = mysqlHelper.GetColString(dt, "nick_name")
	li.MainName = mysqlHelper.GetColString(dt, "main_name")
	li.RegionAddr = mysqlHelper.GetColString(dt, "region_addr")
	li.ContactPeer = mysqlHelper.GetColString(dt, "contact_peer")
	li.Mobile = mysqlHelper.GetColString(dt, "mobile")
	li.BankAccountName = mysqlHelper.GetColString(dt, "bank_account_name")
	li.BankAccount = mysqlHelper.GetColString(dt, "bank_account")
	li.Bank = mysqlHelper.GetColString(dt, "bank")
	num, rooms := getWashRoomNumByLeagueId(li.LeagueId)
	li.WashRoomNum = num
	li.WasherNum = getWasherNumByLeagueId(rooms)
	return li
}
